<?php

/**
 * 云获
 */

declare(strict_types=1);

namespace app\api\controller;

use app\common\func\Tools;
use think\Controller;
use think\Db;

class Yunhuotec extends Controller
{
    // 账号
    private static $username = "HYJvBaoPen@yunhuo";
    // 密码
    private static $password = "yoOWZg2tmLn0aF1O";
    // 客户ID
    private static $clientId = "it93cbe31aj136h6j0z55oyg";
    // 客户密钥
    private static $clientSecret = "779r0ics61r3beh7n0g9orywfs7to771";
    // 平台ID，云获提供
    private static $platformId = "20230614700348900352024576";
    // 这里是云获得公钥(对接信息中也可看到)
    private static $publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDMOjbCr5G/YRCVeyhQWkUY6QhgbbQPjN2Ut3vA3yHGRRb+VuH/DBwTDi65QbP2ykzldlm27Ck6eQCHWxjlHwJfB1zIfNekfsXW50XUqdtCC6EWd7e7bpA5jWQmsiQKCAJa9O7JsdCJJ9kqS/vOfk/NPqILKd4wxtFEsF0EOSXMswIDAQAB";
    // 这里是商户生成的私钥(生成的公钥需要上传到云获平台)
    private static $privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCies1izFWPtqvpgcn6JUv1ReFKhGUDdw3/US3yJe2Pu4WU48II3aVmWruzHZLWB9U8QBjc5RVznRc/KRagI7hez46NZYnF+cNspnhqw9pw7yywpW5U27diYGFnJlAxwfBuJWlr+wz063By0pjAIQhC6IeNuLbcZEa/NZNg9nPDFz74VkF3Vk4v8LMCT32dY4qr5J3s4YET9yJvfvx5zc9NNtC15BcbeDoyZGFVHjsqFL5JmtiYMjOJ4oCEkLxfBQBCjXO1cmWxlreBiKRVfAhEl/qCJRNkqA9U0t9zEQ0JGvD76U4fQkkrHRydNhCryAYKi0aQXsjReN4WtJr+vP/RAgMBAAECggEBAJ+BMLmp4OEZskCk4nRIQv5BIL83o7a4HKyltBZAt6tfqu6UfLqZZLNLpXJcOPcWb3Ybcoz/84QxFk4x9v00s92XotkachtBa2DxN8uQA5TUp6m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xX9MBOKZzpquEaZHYNoq/GZqI=";

    // 获取token地址
    private static $tokenUrl = "http://web.yunhuotec.com/api/oauth/anno/token";
    // 打款接口
    private static $remitUrl = "http://web.yunhuotec.com/api/thirdparty/payment/V2/pay";
    // 订单查询接口
    private static $orderQueryUrl = "http://web.yunhuotec.com/api/thirdparty/order/V2/query";
    // 余额查询接口
    private static $balanceQueryUrl = "http://web.yunhuotec.com/api/thirdparty/platform/V2/query";
    // 充值记录查询接口
    private static $rechargeQueryUrl = "http://web.yunhuotec.com/api/thirdparty/recharge/queryRecord";

    // 打款接口
    public static function remittance($order_number)
    {
        if (!empty($order_number)) {

            $orderData = Db::name("withdrawal_order")->alias("a")
                ->join("user_card b", 'b.sale_id = a.sale_id', 'LEFT')
                ->where('a.order_number', $order_number)->find();

            if (empty($orderData)) {
                return ["code" => 300, "msg" => "无订单信息！"];
            }
            if ($orderData["status"] == 2) {
                return ["code" => 300, "msg" => "订单已作废！"];
            }
            if ($orderData["payment_status"] > 2) {
                return ["code" => 300, "msg" => "订单状态错误！"];
            }
            if (empty($orderData["card_front"]) || empty($orderData["card_back"])) {
                return ["code" => 300, "msg" => "缺少身份证照片"];
            }

            $publicKey = "-----BEGIN PUBLIC KEY-----\n" . wordwrap(self::$publicKey, 64, "\n", true) . "\n-----END PUBLIC KEY-----";
            $privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" . wordwrap(self::$privateKey, 64, "\n", true) . "\n-----END RSA PRIVATE KEY-----";

            //获取token
            $token = self::getToken(self::$tokenUrl, self::$username, self::$password, self::$clientId, self::$clientSecret);

            $data['platformId'] = self::$platformId;
            $data['merOrderNo'] = $orderData["order_number"];
            $data['inAcctName'] = $orderData["name"]; //收款人姓名
            $data['inCidno'] = $orderData["idcards"]; //收款人身份证号码
            $data['inMobile'] = $orderData["phone"]; //收款人手机号
            $data['inAcctNo'] = $orderData["bank_card_number"]; //收款人银行卡号
            $data['amount'] = $orderData["arrival_amount"] * 100; //打款金额（分）
            $data['remark'] = "商户余额提现"; //打款备注
            $data['cidAddress'] = $orderData["address"]; //打款备注

            $rsa_encrypt = self::encrypt($data, $publicKey);

            $sign = self::wjSign($data, $privateKey);

            $fileBase64Str1 = self::imgToBase64('.' . $orderData["card_front"]);
            $fileBase64Str2 = self::imgToBase64('.' . $orderData["card_back"]);

            $post_data = array(
                "encryptStr" => $rsa_encrypt,
                "signStr" => $sign,
                "tenant" => 'MDAwMA==', //固定参数
                'fileBase64Str1' => $fileBase64Str1,
                'fileBase64Str2' => $fileBase64Str2,
            );

            $authorization = self::getAuthorization(self::$clientId, self::$clientSecret);
            $header_data = array(
                'token: ' . $token,
                'tenant: MDAwMA==', //固定参数
                'Authorization: ' . $authorization
            );

            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, self::$remitUrl);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
            curl_setopt($curl, CURLOPT_TIMEOUT, 50000);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt(
                $curl,
                CURLOPT_HTTPHEADER,
                $header_data
            );

            $tmpInfo = curl_exec($curl);
            curl_close($curl);
            $back_res = json_decode($tmpInfo, true);

            if ($back_res["code"] == 0 && $back_res["isSuccess"]) {
                $back_encrypt = json_decode(self::decrypt($back_res['data']['encrypt'], $privateKey), true);
                if ($back_encrypt["rspCod"] == "120000") {
                    return ["code" => 200, "msg" => $back_encrypt["rspMsg"]];
                } else {
                    return ["code" => 300, "msg" => "代付失败，" . $back_encrypt["rspMsg"]];
                }
            } else {
                return ["code" => 300, "msg" => "代付失败，" . $back_res["msg"]];
            }
        } else {
            return ["code" => 300, "msg" => "无订单信息！"];
        }
    }

    public function orderCreate()
    {
        $order_number = "HHR20230829141228520";
        $return = $this->remittance($order_number);
        dump($return);
    }

    public function test()
    {
        $privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" . wordwrap(self::$privateKey, 64, "\n", true) . "\n-----END RSA PRIVATE KEY-----";
        $return = '{"encrypt":"jkA2ydmSFxmVaiNQbUmL2UJRWSofCTbgry1zI5xtwA6ucshtuyRNysfMBHp2tbTI6SAGVkqSclyi5LBzWD4sB+HRGnUrEvI9Y1E\/c\/3+YM2MfaJ7ovEsAttHBtnGAaBav82fVZj0hnh9zJGllsF+YkBE9l6BDdAInB4Xvo+ioZ5TFrJIVrjrfOhGWfw\/gRrTBSwY4r0\/rjmO49O\/128mCWvIbc5rjkATLH1Hvdkfk3fuABCLNGyzwVARL1QXVtfhW4\/58\/bB\/p6WBIfIK7Tg6fDe0hjvQIZtzLw\/\/kzrMpfrHTi4EGQ6vdr1FpJ94xDRnDTf9VMLvdo7FcT2hRzLAX1FtaKHVJTii56h2Wy5ykCXQoK3ukmX9g3iY5Xi15hfeNOTQ0X6xyEqh54xzU7NW5FPJqe41LKX4gZ1t3+BqgER8RK9DBRZeZl0cUjOMJAmn5jFkPtA0I6HkS5gsqkcdqMG5JoMEbVS3xcGNUa39W+7m5E5ZJIO+\/caCq+m0JYzRZDIYGkOzoO9bHkuEZ1Z4vcI+01Xrvab4haGkNp3seJXRHMk6rntvCWsZGICJBmHgAQ\/l7vej5F27zIuWdiP021SEJ\/oudsRyUvEvuCTrvKcCBzMC\/BNXkaA+XA5obAlZWPS\/V7XjEfjKsvfT2XzG0+mxjdIXLv3qz8VMYgOKUo=","sign":"e2I6jVGj4Ze7uKaMEC+ewMlU8tbTSSF3gIeZeQRa\/5nPoNOjXzKDV\/zqyLttiai3QfH8iW67Uonr6cyZIhnQxD4hMpXMd5+zVS+jzbYaNKYnuO+q5I387vinHa\/lPUW3IOY880NO8+yM7U5kz\/D7o0P1ZhUWs1vnOMmsof+e+Kw="}';

        $return = json_decode($return, true);

        $back_encrypt  = self::decrypt($return['encrypt'], $privateKey);

        dump($back_encrypt);
    }

    // 提现回调
    public function notify()
    {
        $params = input();
        if (!empty($params)) {
            file_put_contents('./Withdrawal_yunhuo.log', json_encode($params), FILE_APPEND);
            $privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" . wordwrap(self::$privateKey, 64, "\n", true) . "\n-----END RSA PRIVATE KEY-----";
            $return = json_decode(self::decrypt($params['encrypt'], $privateKey), true);

            $orders = Db::name("withdrawal_order")->where('order_number', $return["merOrderNo"])->find();
            if ($orders["status"] == 1 && $orders["payment_status"] == 1) {
                $dataArray['remarks'] = $return["rspMsg"];
                $dataArray["port_content"] = $params["encrypt"];
                if (isset($return["orderStatus"]) && $return["orderStatus"] == "03") {
                    $dataArray["payment_time"] = time();
                    $dataArray['payment_status'] = 2;                                           # 交易成功
                    $dataArray['port_service_fee'] = $return["outAmt"] / 100;                   # 系统代付金额
                } else {
                    $dataArray["payment_time"] = time();
                    $dataArray['payment_status'] = 3;
                }
                $res = Db::name("withdrawal_order")->where('order_number', $return["merOrderNo"])->update($dataArray);
                if ($res && $dataArray['payment_status'] == 3) {
                    Tools::saveBalance(2, $orders["sale_id"], $orders["withdrawal_money"], 2);
                }
            }
        }
        echo json_encode(["handled" => "SUCCESS"]);
    }

    public static function getToken($url, $username, $password, $clientId, $client_secret)
    {
        $post_data = array(
            "account" => $username,
            "grantType" => "password",
            "password" => $password,
        );
        $authorization = self::getAuthorization($clientId, $client_secret);
        $headers = array(
            "Content-Type" => 'application/json',
            "tenant" => "MDAwMA==",
            "Authorization" => $authorization,
        );
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($post_data));
        curl_setopt($curl, CURLOPT_TIMEOUT, 50000);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt(
            $curl,
            CURLOPT_HTTPHEADER,
            array(
                'Content-Type: application/json',
                'tenant: MDAwMA==',
                'Authorization: ' . $authorization
            )
        );
        $tmpInfo = curl_exec($curl);
        $data = json_decode($tmpInfo, true);
        return "Bearer " . $data['data']['token'];
    }

    /**
     * 图片base64处理
     * @date 2017-02-20 19:41:22
     *
     * @param $img_fileַ
     *
     * @return string
     */
    public static function imgToBase64($img_file)
    {
        $img_base64 = '';
        if (file_exists($img_file)) {
            $app_img_file = $img_file;
            $img_info = getimagesize($app_img_file);
            $fp = fopen($app_img_file, "r");
            if ($fp) {
                $filesize = filesize($app_img_file);
                $content = fread($fp, $filesize);
                $file_content = chunk_split(base64_encode($content));
                switch ($img_info[2]) {
                    case 1:
                        $img_type = "gif";
                        break;
                    case 2:
                        $img_type = "jpg";
                        break;
                    case 3:
                        $img_type = "png";
                        break;
                }
                $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;
            }
            fclose($fp);
        }
        return $img_base64;
    }

    /**
     * 获取Authorization
     *
     * @param $clientId 
     * @param $client_secret 
     * @return string
     */
    public static function getAuthorization($clientId, $client_secret)
    {
        $uniqueFlag = $clientId . ":" . $client_secret;
        $uniqueFlag = "Basic " . base64_encode($uniqueFlag);
        return $uniqueFlag;
    }

    public static function wjSign($params, $privateKey)
    {
        //解决中文乱码问题
        foreach ($params as $key => $value) {
            if (!empty($value) && !is_numeric($value)) {
                $params[$key] = urlencode($value);
            }
        }
        $data = urldecode(json_encode($params));
        openssl_sign($data, $sign, $privateKey, OPENSSL_ALGO_MD5);
        $sign = base64_encode($sign);
        return $sign;
    }

    /**
     * 对参数进行加密
     *
     * @param $params 待加密参数数组
     * @param $publicKey 对端的公钥
     * @return  string base64字符串
     */
    public static function encrypt($params, $publicKey)
    {
        //解决中文乱码问题
        foreach ($params as $key => $value) {
            if (!empty($value) && !is_numeric($value)) {
                $params[$key] = urlencode($value);
            }
        }
        $_rawData = urldecode(json_encode($params));
        $_encryptedList = array();
        $_step = 117;
        $_encrypted = '';
        for ($_i = 0, $_len = strlen($_rawData); $_i < $_len; $_i += $_step) {
            $_data = substr($_rawData, $_i, $_step);
            $_encrypted = '';
            openssl_public_encrypt($_data, $_encrypted, $publicKey);
            $_encryptedList[] = ($_encrypted);
        }
        $_data = base64_encode(join('', $_encryptedList));
        return $_data;
    }



    /**
     * 对参数进行解密
     *
     * @param $encryptedData 待解密参数
     * @param $privateKey 自己的私钥
     * @return string
     */
    public static function decrypt($encryptedData, $privateKey)
    {
        $_encryptedData = base64_decode($encryptedData);
        $_decryptedList = array();
        $_step = 128;
        if (strlen($privateKey) > 1000) {
            $_step = 256;
        }
        for ($_i = 0, $_len = strlen($_encryptedData); $_i < $_len; $_i += $_step) {
            $_data = substr($_encryptedData, $_i, $_step);
            $_decrypted = '';
            openssl_private_decrypt($_data, $_decrypted, $privateKey);
            $_decryptedList[] = $_decrypted;
        }
        return join('', $_decryptedList);
    }
}
